import Vue from 'vue'
import Vuex from 'vuex'

import user from './module/user.js'
import app from './module/app.js'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0,
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false },
    ],
  },
  getters: {
    //通过属性访问--简单示例
    doneTodos: (state) => {
      return state.todos.filter((todo) => todo.done)
    },
    //通过属性访问--使用getters中的其他方法
    undoTodosLength: (state, getters) => {
      return state.todos.length - getters.doneTodos.length
    },
    //通过方法访问--返回的是函数
    getTodoById: (state) => (id) => {
      return state.todos.find((item) => item.id === id)
    },
  },
  mutations: {
    increment(state) {
      state.count++
    },
    increment2(state, amount) {
      // 变更状态
      state.count += amount
    },
    increment3(state, payload) {
      // 变更状态
      state.count += payload.amount
    },
  },
  actions: {
    increment(context) {
      context.commit('increment')
    },
    increment2({ commit }, amount) {
      commit('increment2', amount)
    },
    increment3({ commit }, payload) {
      setTimeout(() => {
        commit('increment3', payload)
      }, 3000)
    },
  },
  modules: { user, app },
})
